<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>创建新账号</h2>
        <p>加入我们，享受更多精彩内容</p>
      </div>

      <form class="register-form" @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="username"
            type="text"
            placeholder="请设置用户名"
            required
          />
        </div>

        <div class="form-group">
          <label for="email">邮箱（可选）</label>
          <input
            id="email"
            v-model="email"
            type="email"
            placeholder="请输入邮箱"
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="password"
            type="password"
            placeholder="请设置密码（6-20位字符）"
            required
          />
          <div v-if="password" class="password-strength">
            <div class="strength-indicators">
              <div :class="['strength-bar', getStrengthClass(1)]"></div>
              <div :class="['strength-bar', getStrengthClass(2)]"></div>
              <div :class="['strength-bar', getStrengthClass(3)]"></div>
            </div>
            <span class="strength-text">{{ getStrengthText() }}</span>
          </div>
        </div>

        <div class="form-group">
          <label for="confirm-password">确认密码</label>
          <input
            id="confirm-password"
            v-model="confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            required
          />
          <div v-if="confirmPassword && password !== confirmPassword" class="error-message">
            两次输入的密码不一致
          </div>
        </div>

        <div class="form-group">
          <label for="phone">手机号码（可选）</label>
          <input
            id="phone"
            v-model="phone"
            type="tel"
            placeholder="请输入手机号码"
          />
        </div>

        <div class="form-group">
          <label for="birthday">出生日期</label>
          <div class="date-input-container">
            <input
              id="birthday"
              v-model="birthday"
              type="date"
              required
              class="date-input"
              :class="{ 'focused': birthdayFocused }"
              @focus="birthdayFocused = true"
              @blur="birthdayFocused = false"
              placeholder="请选择您的出生日期"
            />
            <div class="calendar-icon">
              <i class="icon-calendar"></i>
            </div>
          </div>
          <div v-if="birthday" class="age-display">
            您的年龄：{{ calculateAge(birthday) }}岁
          </div>
          <div v-if="birthday && !validateAge()" class="error-message age-error">
            您必须年满13岁才能注册
          </div>
        </div>

        <div class="form-group terms">
          <input id="terms" v-model="agreeToTerms" type="checkbox" required />
          <label for="terms">
            我已阅读并同意<a href="#">服务条款</a>和<a href="#">隐私政策</a>
          </label>
        </div>

        <button type="submit" class="register-button" :disabled="!isFormValid">注册</button>

        <div class="form-divider">
          <span>或</span>
        </div>

        <div class="social-register">
          <button type="button" class="social-button wechat">
            <i class="icon-wechat"></i>
            <span>微信注册</span>
          </button>
          <button type="button" class="social-button qq">
            <i class="icon-qq"></i>
            <span>QQ注册</span>
          </button>
          <button type="button" class="social-button weibo">
            <i class="icon-weibo"></i>
            <span>微博注册</span>
          </button>
        </div>

        <div class="login-link">
          <p>已有账号？<router-link to="/login">立即登录</router-link></p>
        </div>
      </form>

      <div class="register-footer">
        <p>注册即表示您同意我们的<a href="#">服务条款</a>和<a href="#">隐私政策</a></p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RegisterView',
  data() {
    return {
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      phone: '',
      birthday: '',
      birthdayFocused: false,
      agreeToTerms: false,
      error: '',
    }
  },
  computed: {
    isFormValid() {
      return (
        this.username &&
        this.password &&
        this.confirmPassword &&
        this.birthday &&
        this.password === this.confirmPassword &&
        this.agreeToTerms &&
        this.validateAge()
      )
    },
  },
  mounted() {
    // 如果用户已登录，直接跳转到首页
    if (localStorage.getItem('isLoggedIn') === 'true') {
      this.$router.push('/')
    }
  },
  methods: {
    // 计算用户年龄
    calculateAge(birthday) {
      if (!birthday) return 0;
      const birthDate = new Date(birthday);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      return age;
    },
    
    // 验证年龄，确保用户至少13岁
    validateAge() {
      if (!this.birthday) return false;
      return this.calculateAge(this.birthday) >= 13;
    },
    
    handleRegister() {
      // 这里可以添加实际的注册逻辑
      console.log('注册信息:', {
        username: this.username,
        email: this.email,
        password: this.password,
        phone: this.phone,
      })
      
      // 保存注册用户信息到 localStorage
      const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
      
      const age = this.calculateAge(this.birthday);
      
      const newUser = {
        username: this.username,
        email: this.email,
        password: this.password,
        phone: this.phone,
        birthday: this.birthday,
        age: age,
        createdAt: new Date().toISOString(),
        // 确保新用户数据都为0
        following: 0,
        followers: 0,
        coins: 0,
        level: 0,
        vip: false,
        totalPlays: 0,
        videos: [],
        drafts: [],
      }
      registeredUsers.push(newUser)
      localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers))
      
      // 设置基本用户信息，确保都是默认值
      const userMemberInfo = {
        level: 0,
        vip: false,
        coins: 0,
        memberLevel: 0,
        growthValue: 0,
      }
      
      localStorage.setItem('userMemberInfo', JSON.stringify(userMemberInfo))
      
      // 模拟注册成功
      alert('注册成功！')
      
      // 跳转到登录页面
      this.$router.push('/login')
    },
    handleSocialRegister(provider) {
      console.log('社交注册:', provider)
      // 这里可以添加社交注册的逻辑
    },
    getPasswordStrength() {
      // 简单的密码强度检测
      if (!this.password) return 0
      
      let strength = 0
      
      // 长度检测
      if (this.password.length >= 8) strength++
      if (this.password.length >= 12) strength++
      
      // 复杂性检测
      if (/[A-Z]/.test(this.password)) strength++
      if (/[a-z]/.test(this.password)) strength++
      if (/[0-9]/.test(this.password)) strength++
      if (/[^A-Za-z0-9]/.test(this.password)) strength++
      
      // 返回1-3的强度等级
      return Math.min(3, Math.floor(strength / 2))
    },
    getStrengthClass(level) {
      const strength = this.getPasswordStrength()
      if (level <= strength) {
        if (strength === 1) return 'weak'
        if (strength === 2) return 'medium'
        if (strength === 3) return 'strong'
      }
      return ''
    },
    getStrengthText() {
      const strength = this.getPasswordStrength()
      if (strength === 1) return '弱'
      if (strength === 2) return '中'
      if (strength === 3) return '强'
      return ''
    },
  },
}
</script>

<style scoped>
.register-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: var(--bg-color);
  padding: 20px;
}

.register-box {
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 500px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 28px;
  font-weight: bold;
  color: var(--text-color);
  margin-bottom: 10px;
}

.register-header p {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0;
}

.register-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color);
  margin-bottom: 8px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  font-size: 16px;
  color: var(--text-color);
  background-color: var(--bg-color);
  transition: all 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(236, 72, 153, 0.1);
}

/* 日期输入框样式优化 */
.date-input-container {
  position: relative;
  margin-bottom: 4px;
}

.date-input {
  padding-right: 40px !important;
  background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
  transition: all 0.3s ease;
}

.date-input:focus,
.date-input.focused {
  border-color: var(--primary-color);
  background-image: linear-gradient(120deg, #ffffff 0%, #f8f9fa 100%);
  box-shadow: 0 0 0 3px rgba(236, 72, 153, 0.2);
  transform: translateY(-1px);
}

.calendar-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-secondary);
  pointer-events: none;
  font-size: 18px;
  opacity: 0.7;
  transition: all 0.3s ease;
}

.date-input:focus + .calendar-icon,
.date-input.focused + .calendar-icon {
  color: var(--primary-color);
  opacity: 1;
  transform: translateY(-50%) scale(1.1);
}

/* 年龄显示样式 */
.age-display {
  font-size: 14px;
  color: var(--primary-color);
  margin-top: 6px;
  font-weight: 500;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-5px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 年龄错误提示样式增强 */
.age-error {
  animation: shake 0.5s ease;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

.password-strength {
  margin-top: 8px;
}

.strength-indicators {
  display: flex;
  gap: 4px;
  margin-bottom: 4px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  background-color: #e5e7eb;
  transition: all 0.3s ease;
}

.strength-bar.weak {
  background-color: #ef4444;
}

.strength-bar.medium {
  background-color: #f59e0b;
}

.strength-bar.strong {
  background-color: #10b981;
}

.strength-text {
  font-size: 12px;
  color: var(--text-secondary);
}

.error-message {
  font-size: 12px;
  color: #ef4444;
  margin-top: 8px;
}

.form-group.terms {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 24px;
}

.form-group.terms input[type="checkbox"] {
  width: auto;
  margin-top: 2px;
}

.form-group.terms label {
  margin: 0;
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.4;
}

.form-group.terms a {
  color: var(--primary-color);
  text-decoration: none;
}

.form-group.terms a:hover {
  text-decoration: underline;
}

.register-button {
  width: 100%;
  padding: 12px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.register-button:hover:not(:disabled) {
  background-color: var(--primary-hover);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(236, 72, 153, 0.3);
}

.register-button:active:not(:disabled) {
  transform: translateY(0);
}

.register-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.form-divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.form-divider::before,
.form-divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: var(--border-color);
}

.form-divider span {
  padding: 0 16px;
  font-size: 14px;
  color: var(--text-secondary);
}

.social-register {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.social-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16px 8px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background-color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
}

.social-button:hover {
  border-color: var(--primary-color);
  background-color: var(--hover-color);
}

.social-button span {
  margin-top: 8px;
  color: var(--text-color);
}

.social-button.wechat:hover {
  border-color: #07C160;
  color: #07C160;
}

.social-button.qq:hover {
  border-color: #12B7F5;
  color: #12B7F5;
}

.social-button.weibo:hover {
  border-color: #E6162D;
  color: #E6162D;
}

.login-link {
  text-align: center;
  margin-bottom: 20px;
}

.login-link p {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.login-link a {
  color: var(--primary-color);
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.login-link a:hover {
  text-decoration: underline;
}

.register-footer {
  text-align: center;
}

.register-footer p {
  font-size: 12px;
  color: var(--text-secondary);
  margin: 0;
  line-height: 1.6;
}

.register-footer a {
  color: var(--primary-color);
  text-decoration: none;
}

.register-footer a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .register-box {
    padding: 30px 20px;
  }
  
  .register-header h2 {
    font-size: 24px;
  }
  
  .social-register {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .social-button {
    padding: 12px 4px;
    font-size: 11px;
  }
}
</style>